<template>
  <div class="container" v-loading="loading">
    <div id="map" class="map" :class="{ 'lazy-in': init }"></div>
    <div class="layout">
      <!--头部-->
      <div v-if="init" class="header">
        <div class="search">
          <el-input
            v-model="searchKey"
            style="width: 100%"
            placeholder="搜索"
            @keydown.enter="search"
          />
        </div>
        <div class="user" v-if="!userInfo" @click="loginVisible = true">
          登录
        </div>
        <div
          class="user-info"
          v-else
          ref="buttonRef"
          v-click-outside="onClickOutside"
        >
          <img class="user-info-avatar" :src="userInfo.avatar || AVATAR"  alt=""/>
          <div class="user-info-name">{{ userInfo.nickname }}</div>
        </div>
      </div>
      <!--左边导航-->
      <div
        v-if="userInfo"
        class="left-bar"
        :class="{ 'left-bar-expand': expand }"
      >
        <div class="expand" @click="expand = !expand"></div>
        <div class="msg-count">
          私信{{ allUnRead ? `（${allUnRead}）` : '' }}
        </div>
        <div class="ai" @click="aiVisible = true">
          <img src="./assets/im_list_ai1.png" alt="" />
          <div>AI智能问答</div>
        </div>
        <div class="bar-line"></div>
        <div class="user-list">
          <div
            v-for="item in messageList"
            class="user-item"
            :class="{ 'user-checked': activeIM === item.memberId }"
            @click="openIM(item)"
          >
            <img :src="item.avatar || AVATAR" alt="" />
            <div class="online-dot"></div>
            <div class="user-nickname">{{ item.memberName }}</div>
            <div class="user-msg-count" v-if="item.unreadCount">
              {{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
            </div>
          </div>
        </div>
      </div>
      <!--网页底部-->
      <div v-if="init" class="footer" :class="{ 'footer-in': init }">
        <a href="https://beian.miit.gov.cn/" target="_blank">浙ICP备2023000956号-1</a>
        <div>宁波跨世信息技术有限公司 商务邮箱<a href="mailto:ben@crushnear.com">ben@crushnear.com</a></div>
      </div>
      <!--toolbar-->
      <div v-if="userInfo" class="toolbar" :class="{ 'toolbar-in': init }">
        <div class="play" @click="openVideo" v-loading="loadingVideo"></div>
        <div class="setting" @click="infoVisible = true"></div>
      </div>
      <div v-if="userInfo" class="toolbar toolbar-center" :class="{ 'toolbar-in': init }">
        <div class="go-back" @click="goCenter"></div>
      </div>
      <div v-if="showDayBtn" class="day-tool">
        <el-radio-group v-model="currentDay" size="large">
          <el-radio-button v-for="(day,index) in Object.keys(currentLineMap.route).filter(d=>currentLineMap.route[d])" :label="'第'+arabicToChinese(index+1)+'天'" :value="day" :key="index" />
        </el-radio-group>
        <el-button style="margin-left: 12px" :icon="MapLocation" size="large" @click="resetMapLine" />
        <el-button style="margin-left: 12px" type="danger" :icon="CloseBold" size="large" @click="clearMapLine" />
      </div>
      <div v-if="showCLearBtn" class="day-tool">
        <el-button style="margin-left: 12px" :icon="MapLocation" size="large" @click="resetMapLine" />
        <el-button type="danger" :icon="CloseBold" size="large" @click="clearMapLine" />
      </div>
    </div>
    <!--登录弹窗-->
    <el-dialog
      v-model="loginVisible"
      width="810"
      center
      align-center
      :lock-scroll="false"
      :show-close="false"
      destroy-on-close
      class="login-dialog"
    >
      <img
        class="login-close1"
        src="./assets/ic_close@2x.png"
        alt=""
        @click="loginVisible = false"
      />
      <div class="login-content">
        <div class="login-left"></div>
        <div class="login-right">
          <el-input
            class="login-input"
            v-model="phone"
            style="width: 100%"
            placeholder="请输入手机号"
          />
          <el-input
            class="login-input login-code"
            v-model="code"
            style="width: 100%"
            placeholder="请输入验证码"
          />
          <div
            class="get-code"
            :class="{ 'get-code-disabled': second }"
            @click="getCode"
          >
            {{ second ? `${second}s后重新发送` : '获取验证码' }}
          </div>
          <div
            class="login-btn"
            :class="{ 'login-btn-disabled': !code || !phone }"
            @click="loginPhone"
          >
            登录
          </div>
        </div>
      </div>
    </el-dialog>
    <!--用户信息设置-->
    <el-dialog
      v-model="infoVisible"
      width="463"
      center
      align-center
      :lock-scroll="false"
      :show-close="false"
      destroy-on-close
      class="info-dialog"
    >
      <img
        class="login-close"
        src="./assets/ic_close@2x.png"
        alt=""
        @click="infoVisible = false"
      />
      <div class="info-avatar">
        <el-upload
          style="line-height: 0"
          accept="image/*"
          :show-file-list="false"
          :headers="{
            'Tenant-Id': '1',
            Authorization: 'Bearer ' + token,
          }"
          :on-success="afterAvatarUpload"
          :action="baseUrl + '/app-api/infra/file/upload'"
        >
          <img :src="userInfoSetting.avatar || AVATAR" alt="" />
        </el-upload>
      </div>
      <div class="info-avatar-tip">上传头像</div>
      <div class="info-sex">
        <div
          style="margin-right: 23px"
          :class="{ 'info-sex-active': userInfoSetting.sex === 1 }"
          @click="userInfoSetting.sex = 1"
        >
          <img :src="userInfoSetting.sex === 1 ? BOY1 : BOY2" alt="" />
          <div>男生</div>
        </div>
        <div
          :class="{ 'info-sex-active': userInfoSetting.sex === 2 }"
          @click="userInfoSetting.sex = 2"
        >
          <img :src="userInfoSetting.sex === 2 ? GIRL1 : GIRL2" alt="" />
          <div>女生</div>
        </div>
      </div>
      <div class="info-input-content">
        <el-input
          class="info-input"
          v-model="userInfoSetting.nickname"
          style="width: 100%"
          placeholder="昵称"
        />
        <el-input
          class="info-input"
          v-model="userInfoSetting.mark"
          :rows="4"
          :autosize="{ maxRows: 4, minRows: 4 }"
          type="textarea"
          style="width: 100%"
          placeholder="用一句话介绍自己"
        ></el-input>
      </div>
      <div
        class="info-submit"
        :class="{
          'info-submit-active':
            userInfoSetting.nickname &&
            userInfoSetting.sex &&
            userInfoSetting.avatar,
        }"
        @click="updateUserInfo"
      >
        确定
      </div>
    </el-dialog>
    <!--用户信息-->
    <el-popover
      v-if="userInfo"
      ref="popoverRef"
      width="325"
      :virtual-ref="buttonRef"
      trigger="click"
      virtual-triggering
    >
      <div class="user-content">
        <img :src="userInfo.avatar || AVATAR" alt="" />
        <div class="user-content-info">
          <div>{{ userInfo.nickname }}</div>
          <img v-if="userInfo.sex === 1" :src="BOY2" alt="" />
          <img v-else :src="GIRL2" alt="" />
        </div>
      </div>
      <div class="user-logout" @click="logout">退出登录</div>
    </el-popover>
    <!--IM界面-->
    <el-dialog
      v-model="imVisible"
      width="600"
      center
      align-center
      :lock-scroll="false"
      :show-close="false"
      destroy-on-close
      class="im-dialog"
    >
      <img
        class="im-close"
        src="./assets/ic_close@2x.png"
        alt=""
        @click="imVisible = false"
      />
      <div class="im-title">{{ imUserInfo.memberName }}</div>
      <div
        ref="imCtx"
        class="im-content"
        v-loading="loadingIM"
        element-loading-text="正在获取聊天记录..."
      >
        <template v-for="(msg, index) in imMessageList" :key="msg.id">
          <message-time
            :currTime="msg.createTime / 1000"
            :prevTime="
              imMessageList[index - 1]?.createTime
                ? imMessageList[index - 1]?.createTime / 1000
                : undefined
            "
          />
          <div class="im-msg-other" v-if="msg.fromUid === imUserInfo.memberId">
            <img class="im-msg-icon" :src="imUserInfo.avatar" />
            <template v-if="msg.type === 1">
              <div class="im-msg-content" v-if="emojiMap[msg.text]">
                <img :src="emojiMap[msg.text]" alt="" />
              </div>
              <div class="im-msg-content" v-else>{{ msg.text }}</div>
            </template>
            <el-image
              v-if="msg.type === 2"
              class="im-msg-img"
              :src="msg.attrs"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[msg.attrs]"
              show-progress
              fit="cover"
            />
            <video v-if="msg.type === 3" class="im-msg-img" :src="msg.attrs" />
          </div>
          <div class="im-msg-i" v-if="msg.fromUid === userInfo.id">
            <img class="im-msg-icon" :src="userInfo.avatar" alt="" />
            <template v-if="msg.type === 1">
              <div class="im-msg-content" v-if="emojiMap[msg.text]">
                <img :src="emojiMap[msg.text]" alt="" />
              </div>
              <div class="im-msg-content" v-else>{{ msg.text }}</div>
            </template>
            <el-image
              v-if="msg.type === 2"
              class="im-msg-img"
              :src="msg.attrs"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[msg.attrs]"
              show-progress
              fit="cover"
            />
            <video
              v-if="msg.type === 3"
              controls
              class="im-msg-video"
              :src="msg.attrs"
            />
          </div>
        </template>
      </div>
      <div
        class="im-footer"
        v-loading="loadingSend"
        element-loading-background="#00000020"
      >
        <div class="im-footer-content">
          <el-input
            v-model="textarea"
            :rows="2"
            type="textarea"
            placeholder="发送消息"
            @keydown.enter="sendText"
          ></el-input>
          <div class="im-footer-toolbar">
            <div class="ai-del" @click="textarea = undefined" v-if="textarea"></div>
            <div ref="emojiRef" class="toolbar-item toolbar-emoji"></div>
            <el-upload
              style="line-height: 0"
              accept="image/*,video/*"
              :show-file-list="false"
              :headers="{
                'Tenant-Id': '1',
                Authorization: 'Bearer ' + token,
              }"
              :before-upload="() => (loadingSend = true)"
              :on-success="afterUpload"
              :on-error="() => (loadingSend = false)"
              :action="baseUrl + '/app-api/infra/file/upload'"
            >
              <div class="toolbar-item toolbar-file"></div>
            </el-upload>
            <div
              v-if="!textarea"
              class="toolbar-item toolbar-send-disabled"
            ></div>
            <div
              v-else
              class="toolbar-item toolbar-send"
              @click="sendText"
            ></div>
          </div>
        </div>
      </div>
    </el-dialog>
    <!--AI界面-->
    <el-dialog
      v-model="aiVisible"
      width="600"
      center
      align-center
      :lock-scroll="false"
      :show-close="false"
      class="im-dialog"
    >
      <img
        class="im-close"
        src="./assets/ic_close@2x.png"
        alt=""
        @click="aiVisible = false"
      />
      <div class="im-title">crush ai{{ loadingSend ? '（正在回答中...）': loadingLine ? '（正在生成线路中...）' : '' }}</div>
      <div ref="aiCtx" class="ai-content">
        <template v-for="(msg, index) in aiMessageList" :key="msg.id">
          <message-time
            :currTime="msg.time / 1000"
            :prevTime="
              aiMessageList[index - 1]?.time
                ? aiMessageList[index - 1]?.time / 1000
                : undefined
            "
          />
          <div class="ai-msg-other" v-if="msg.ai">
            <img class="im-msg-icon" src="./assets/im_ai@2x.png" alt="" />
            <div class="im-msg-content" v-if="!msg.text && loadingSend">
              正在思考中...
            </div>
            <div
              class="im-msg-content text-blue-4"
              v-if="!msg.text && !loadingSend"
            >
              未获取到信息
            </div>
            <TypingEffect v-else-if="msg.text" :text="msg.text" :showCursor="!msg.ready" @update="updateAIText(index)" @ok="textAllShow(index)" />
          </div>
          <div class="im-msg-i" v-else>
            <img class="im-msg-icon" :src="userInfo.avatar || AVATAR" alt="" />
            <div class="im-msg-content">{{ msg.text }}</div>
          </div>
          <div
            v-if="msg.json && msg.showBtn && (!loadingSend || msg.ready)"
            class="im-msg-btn"
            @click="createMapLine(msg.json)"
          >
            查看详情
          </div>
        </template>
      </div>
      <div
        class="im-footer"
        element-loading-background="#00000020"
      >
        <div class="ai-footer-content">
          <el-input
            style="flex: 1"
            v-model="textarea"
            :rows="1"
            :disabled="loadingSend"
            type="textarea"
            placeholder="发送消息"
            @keydown.enter="sendAiText"
          ></el-input>
          <div class="ai-del" @click="textarea = undefined" v-if="textarea"></div>
          <div
            v-if="!textarea"
            class="toolbar-item toolbar-send-disabled"
          ></div>
          <div
            v-else
            class="toolbar-item toolbar-send"
            @click="sendAiText"
          ></div>
        </div>
      </div>
    </el-dialog>
    <!--视频播放-->
    <el-dialog
      v-model="videoVisible"
      width="540"
      align-center
      :lock-scroll="false"
      :show-close="false"
      destroy-on-close
      class="video-dialog"
    >
      <img
        class="video-close"
        src="./assets/ic_close1@2x.png"
        alt=""
        @click="videoVisible = false"
      />
      <swiper
        class="video-content"
        slides-per-view="1"
        direction="vertical"
        :centeredSlides="true"
        :loop="false"
        :scrollbar="false"
        :navigation="{
          nextEl: '#page-ctr-nxt',
          prevEl: '#page-ctr-pre',
        }"
        @swiper="onSwiper"
        @slideChange="onSlideChange"
      >
        <swiper-slide
          class="swiper-item"
          v-for="(v, index) in videoList"
          :key="v.id"
          :style="{
            opacity: activeVideo === index ? '1' : '0',
            transition: 'opacity 0.3s',
          }"
        >
          <video
            :id="v.id"
            width="100%"
            height="auto"
            loop
            :src="v.video"
            :poster="v.cover"
          ></video>
        </swiper-slide>
      </swiper>
      <div class="page-ctr">
        <img
          id="page-ctr-pre"
          class="page-ctr-pre"
          :class="{
            'page-ctr-pre-disabled': !(videoList.length && activeVideo),
          }"
          :src="videoList.length && activeVideo ? PRE : NXT"
          alt=""
        />
        <img
          id="page-ctr-nxt"
          class="page-ctr-nxt"
          :class="{
            'page-ctr-nxt-disabled': !(
              videoList.length && activeVideo + 1 !== videoList.length
            ),
          }"
          :src="
            videoList.length && activeVideo + 1 !== videoList.length ? PRE : NXT
          "
          alt=""
        />
      </div>
      <div class="video-info">
        <div class="video-title">{{ videoList[activeVideo].title }}</div>
        <div class="video-time">
          {{
            calculateTimestamp({
              createTime: videoList[activeVideo].createTime,
              status: -1,
            })
          }}
        </div>
      </div>
    </el-dialog>
    <!--emoji-->
    <el-popover
      ref="emojiPopoverRef"
      width="548"
      popper-class="emoji-popper"
      placement="top"
      :virtual-ref="emojiRef"
      trigger="click"
      virtual-triggering
    >
      <div class="emoji-box">
        <img
          v-for="(emoji, index) in Object.keys(emojiMap)"
          :key="index"
          :src="emojiMap[emoji]"
          alt=""
          @click="sendEmoji(emoji)"
        />
      </div>
    </el-popover>
    <!--活动详情-->
    <el-drawer
      v-model="drawerVisible"
      :with-header="false"
      destroy-on-close
      :size="575"
    >
      <div style="position: relative">
        <div class="drawer-close">
          <img
            src="./assets/ic_close@2x.png"
            alt=""
            @click="drawerVisible = false"
          />
        </div>
        <div style="margin: 10px 16px" v-html="activityDetail"></div>
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  computed,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  unref,
  watch,
} from 'vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ClickOutside as vClickOutside, ElMessage } from 'element-plus'
import { CloseBold, MapLocation } from '@element-plus/icons-vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { emojiMap } from './utils/emoji.js'
import MAN from '@/assets/ic_man@2x.png'
import GIRL from '@/assets/ic_girl@2x.png'
import BOY1 from '@/assets/boy-white.png'
import BOY2 from '@/assets/boy-color.png'
import GIRL1 from '@/assets/girl-white.png'
import GIRL2 from '@/assets/girl-color.png'
import USER from '@/assets/user.png'
import AVATAR from '@/assets/avatar.png'
import NXT from '@/assets/btn_nxt@2x.png'
import PRE from '@/assets/btn_pre@2x.png'
import Location from '@/assets/Location.png'
import MessageTime from '@/components/MessageTime.vue'
import TypingEffect from "@/components/typing-effect.vue";

const baseUrl = 'http://121.41.226.80:48080'
// const baseUrl = 'http://home.lksyy.com:48080'

axios.defaults.baseURL = baseUrl
axios.defaults.headers.common['Tenant-Id'] = '1'

const colorMap = {
  0: '#000000',
  1: '#6F8CFF',
  2: '#FF9E17',
  3: '#FF9E17',
  4: '#FF9E17',
}
const statusMap = {
  0: '活动草稿中~',
  1: '活动准备中~',
  2: '活动报名中~',
  3: '活动报名结束~',
  4: '活动已结束~',
}

const md = new MarkdownIt({
  html: true,
  xhtmlOut: true,
  linkify: true,
  typographer: true,
  breaks: true,
  highlight: (code, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (_) {}
    }
    return ''
  },
})
let map = null
let driving = null
let userCardMarker = null
let allRouteMarkers = []
const token = ref('')
const loading = ref(true)
const loadingIM = ref(false)
const loadingSend = ref(false)
const loadingVideo = ref(false)
const loadingLine = ref(false)
const init = ref(false)
const searchKey = ref('')
const loginVisible = ref(false)
const imVisible = ref(false)
const aiVisible = ref(false)
const videoVisible = ref(false)
const drawerVisible = ref(false)
const infoVisible = ref(false)
const expand = ref(false)
const phone = ref('')
const code = ref('')
const second = ref(0)
const userInfo = ref(null)
const userInfoSetting = ref(null)
const buttonRef = ref()
const popoverRef = ref()
const emojiRef = ref()
const emojiPopoverRef = ref()
const swiperInstance = ref()
const aiCtx = ref()
const imCtx = ref()
const textarea = ref('')
const activityDetail = ref('')
const activeIM = ref(-1)
const activeVideo = ref(0)
const videoList = ref([])
const messageList = ref([])
const imUserInfo = ref(null)
const imMessageList = ref([])
const aiMessageList = ref([])
const currentLineMap = ref(null)
const markerList = ref([])
const hasMarkerActive = ref(false)
const intervalIM = ref(0)
const currentDay = ref('')
const showDayBtn = ref(false)
const showCLearBtn = ref(false)

const allUnRead = computed(() => {
  return messageList.value.reduce((total, item) => {
    return total + item.unreadCount
  }, 0)
})

watch(
  () => activeVideo.value,
  (val, old) => {
    const videoOld = document.getElementById(videoList.value[old].id)
    videoOld?.pause()
    const video = document.getElementById(videoList.value[val].id)
    video?.load()
    video?.play()
  }
)

watch(
  () => token.value,
  async (val) => {
    if (val) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${val}`
      await Promise.all([getUserInfo(), getUserMessageList()])
      setInterval(() => {
        getUserMessageList()
      }, 10000)
      init.value = true
      loading.value = false
    } else {
      delete axios.defaults.headers.common['Authorization']
    }
  }
)
watch(
  () => imVisible.value,
  (val) => {
    clearInterval(intervalIM.value)
    if (!val) {
      textarea.value = undefined
      activeIM.value = -1
    } else {
      intervalIM.value = setInterval(() => {
        getIMMessageList()
      }, 5000)
    }
  }
)
watch(
  () => aiVisible.value,
  (val) => {
    if (!val) {
      textarea.value = undefined
    } else {
      setTimeout(() => {
        scrollToBottom('.ai-content')
      }, 500)
    }
  }
)
watch(
  () => infoVisible.value,
  (val) => {
    if (val) userInfoSetting.value = JSON.parse(JSON.stringify(userInfo.value))
  }
)
watch(
  () => aiMessageList.value.length,
  () => {
    nextTick(() => {
      scrollToBottom('.ai-content')
    })
  }
)
watch(()=>currentDay.value, (val)=> {
  if (!val) return
  if (allRouteMarkers?.length > 0) {
    allRouteMarkers.forEach((item) => {
      map.remove(item.marker)
    })
    allRouteMarkers = []
  }
  const allAddr = currentLineMap.value.route[val]
  if (!allAddr) return
  if (driving) driving.clear()
  // 根据起终点经纬度规划驾车导航路线
  if (allAddr.length > 1) {
    let waypoints = allAddr.slice(1, -1);
    driving.search(
      new AMap.LngLat(allAddr[0].longitude, allAddr[0].latitude),
      new AMap.LngLat(allAddr[allAddr.length - 1].longitude, allAddr[allAddr.length - 1].latitude),
      {
        waypoints: waypoints.map((item) => {
          return new AMap.LngLat(item.longitude, item.latitude)
        })
      }
    )
  } else if (allAddr.length === 1) {
    map.setCenter([allAddr[0].longitude, allAddr[0].latitude])
  }
  allAddr.forEach((item) => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(item.longitude, item.latitude),
      icon: Location,
      anchor:'bottom-center',
      offset: new AMap.Pixel(0, 0),
      extData: item,
      zIndex: 2,
      clickable: true,
    })
    marker.on('click', onRouteMarkerClick)
    map.add(marker)
    allRouteMarkers.push({ ...item,marker: marker })
  })
  resetMapLine()
})

onMounted(() => {
  token.value = localStorage.getItem('token') || ''

  AMapLoader.load({
    key: '4415811e48ab2dd1ff6dbd566ec147f6',
    // key: 'c8dc4cc140ab75b9b21bd0eaf8bc0cd8',
    version: '2.0',
    plugins: [
      'AMap.Marker',
      'AMap.Pixel',
      'AMap.LngLat',
      'AMap.Geolocation',
      'AMap.Driving',
    ],
  })
    .then(async (AMap) => {
      // const res = await getLocation()
      map = new AMap.Map('map', {
        viewMode: '3D',
        terrain: true,
        zoom: 18,
        zooms: [12, 20],
        pitch: 65,
        center: [121.614253, 29.861748],
      })
      map.on('click', onMapClick)
      driving = new AMap.Driving({
        map: map,
        hideMarkers: true,
      })
    })
    .catch((e) => {
      ElMessage.error({
        message: '地图初始化失败',
      })
      console.log(e)
    })
    .finally(() => {
      if (!token.value) {
        init.value = true
        setTimeout(() => {
          loading.value = false
        }, 300)
      }
      createUserCard()
      getMapMarker()
    })
})

onUnmounted(() => {
  map?.destroy()
})

const getLocation = () => {
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.Geolocation', function () {
      const geolocation = new AMap.Geolocation({
        showButton: false,
        showCircle: false,
        showMarker: false,
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 10000, //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      })
      geolocation.getCurrentPosition(onComplete, onError)
    })
    function onComplete(data) {
      resolve(data)
    }
    function onError(data) {
      reject(data)
    }
  })
}

const get = (url, data) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: data,
      })
      .then((res) => {
        if (res.data.code === 200 || res.data.code === 0) {
          resolve(res.data.data)
        } else if (res.data.code === 401) {
          ElMessage.error({
            message: '登录过期，请重新登录',
          })
          logout()
        } else {
          ElMessage.error({
            message: res.data.msg,
          })
          reject()
        }
      })
      .catch((e) => {
        reject(e)
      })
  })
}

const put = (url, data) => {
  return new Promise((resolve, reject) => {
    axios
      .put(url, data)
      .then((res) => {
        if (res.data.code === 200 || res.data.code === 0) {
          resolve(res.data.data)
        } else if (res.data.code === 401) {
          ElMessage.error({
            message: '登录过期，请重新登录',
          })
          logout()
        } else {
          ElMessage.error({
            message: res.data.msg,
          })
          reject()
        }
      })
      .catch((e) => {
        reject(e)
      })
  })
}

const post = (url, data, config = undefined) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, config)
      .then((res) => {
        if (res.data.code === 200 || res.data.code === 0) {
          resolve(res.data.data)
        } else if (res.data.code === 401) {
          ElMessage.error({
            message: '登录过期，请重新登录',
          })
          logout()
        } else {
          ElMessage.error({
            message: res.data.msg,
          })
          reject()
        }
      })
      .catch((e) => {
        reject(e)
      })
  })
}

const getCode = () => {
  if (second.value) return
  const reg = /^1[3456789]\d{9}$/
  if (!reg.test(phone.value))
    return ElMessage.warning({
      message: '请输入正确的手机号',
    })
  post(`/app-api/member/auth/send-sms-code`, { mobile: phone.value, scene: 1 })
    .then((res) => {
      ElMessage.success({
        message: '发送成功',
      })
      getCodeTimer()
    })
    .catch((e) => {
      ElMessage.warning({
        message: '发送失败',
      })
    })
}

const getCodeTimer = () => {
  if (!second.value) second.value = 60
  setTimeout(() => {
    second.value--
    if (second.value) getCodeTimer()
  }, 1000)
}

const loginPhone = () => {
  if (!phone.value)
    return ElMessage.warning({
      message: '请输入手机号',
    })
  if (!code.value)
    return ElMessage.warning({
      message: '请输入验证码',
    })
  post(`/app-api/member/auth/sms-login`, {
    mobile: phone.value,
    code: code.value,
  }).then((res) => {
    ElMessage.success({
      message: '登录成功',
    })
    token.value = res.accessToken
    localStorage.setItem('token', res.accessToken)
    loginVisible.value = false
  })
}

const getUserInfo = async () => {
  userInfo.value = await get(`/app-api/member/user/get`)
}

const getUserMessageList = async () => {
  messageList.value =
    (await get(`/app-api/crush/member-message/unread-count`)) || []
}

const getIMMessageList = async () => {
  const { list } = await get(`/app-api/crush/member-message/latest`, {
    pageNo: 1,
    pageSize: 100,
    toUid: imUserInfo.value.memberId,
  })
  const hasNew =
    list.length !== imMessageList.value.length ||
    list[0]?.id !== imMessageList.value[0]?.id
  imMessageList.value = list?.reverse() || []
  if (hasNew) {
    setTimeout(() => {
      scrollToBottom('.im-content')
    }, 500)
    await readMessage()
  }
}

const readMessage = async () => {
  await post(`app-api/crush/member-message/mark-as-read`, {
    messageIds: imMessageList.value.map((i) => i.id),
  })
  await getUserMessageList()
}

const scrollToBottom = (content) => {
  try {
    const target = content === '.ai-content' ? aiCtx.value : imCtx.value
    const { height } = target.getBoundingClientRect()
    target.scrollTo({
      top: target.scrollHeight - height,
      behavior: 'smooth',
    })
  } catch (e) {}
}

const logout = () => {
  token.value = ''
  clearUserInfo()
  ElMessage.success({
    message: '退出成功',
    duration: 500,
    onClose: () => {
      location.reload()
    },
  })
}

const clearUserInfo = () => {
  localStorage.removeItem('token')
}

const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.()
}

const openIM = (item) => {
  loadingIM.value = true
  imMessageList.value = []
  imUserInfo.value = item
  activeIM.value = item.memberId
  imVisible.value = true
  getIMMessageList().finally(() => {
    loadingIM.value = false
  })
}

const onSwiper = (swiperRef) => {
  activeVideo.value = 0
  const video = document.getElementById(videoList.value[0].id)
  video?.play()
  swiperInstance.value = swiperRef
}

const onSlideChange = (e) => {
  activeVideo.value = e.activeIndex
}

const setMapMarker = (item, index) => {
  const marker = new AMap.Marker({
    position: [item.longitude, item.latitude],
    content: getMarkerContent(item, colorMap[item.itemType], item.itemType),
    offset: new AMap.Pixel(-24, -56),
    extData: item,
    zIndex: 1,
  })
  marker.on('click', onMarkerClick)
  markerList.value[index].marker = marker
  map.add(marker)
}

const getMarkerContent = (item, color, type) => {
  return `<div style="position: relative;width: 50px;height: 60px;">
  <div style="display: flex; width: 50px;height: 50px;box-sizing: border-box;box-shadow: 0 0 10px 0 rgba(0,0,0,0.11);border-radius: ${type === 0 ? '50%':'12px'};background: white;border: 2px solid ${type === 0 ? 'white':color};">
    <img src="${
    item.icon || AVATAR
  }" style="width: 40px;height: 40px;border-radius: 20px;margin: auto"  alt="" />
  </div>
  <div style="position: absolute;width: 8px;height: 8px;background: ${color};border-radius: 4px;left: 50%;bottom: 0;transform: translateX(-50%)"></div>
</div>`
}
const getMarkerActiveContent = (item, color, type) => {
  return `<div style="position: relative;width: 88px;height: 108px;">
  <div style="display: flex; width: 88px;height: 88px;box-sizing: border-box;box-shadow: 0 0 10px 0 rgba(0,0,0,0.11);border-radius: ${type === 0 ? '50%':'21px'};background: white;border: 4px solid ${type === 0 ? 'white':color};">
    <img src="${
    item.icon || AVATAR
  }" style="width: 70px;height: 70px;border-radius: 35px;margin: auto"  alt="" />
  </div>
  <div style="position: absolute;width: 14px;height: 14px;background: ${color};border-radius: 7px;left: 50%;bottom: 0;transform: translateX(-50%)"></div>
</div>`
}
const getUserCardContent = (item = {}) => {
  return `<div style="position: relative;width: 378px;height: 180px;">
  <div style="display: flex; width: 378px;height: 173px;box-sizing: border-box;box-shadow: 0 0 10px 0 rgba(0,0,0,0.11);border-radius: 12px;background: white;position: relative;z-index: 2;padding: 16px">
    <img src="${
    item.avatar || AVATAR
  }" style="width: 86px;height: 86px;border-radius: 43px;margin-right: 12px"  alt="" />
    <div style="flex: 1;">
      <div style="display: flex;justify-items: center;align-items: center;margin-bottom: 8px;">
        <div style="line-height: 25px;font-weight: 600;font-size: 18px;color: #333333;width: max-content;margin-right: 8px">${
    item.nickname
  }</div>
        <img style="width: 18px;height: 18px;" src="${
    item.sex === 2 ? GIRL : MAN
  }" alt="">
      </div>
      <div style="font-size: 16px; color: #333333;margin-bottom: 8px;height: 66px;line-height: 22px;" class="ellipsis3">${
    item.mark || '暂无简介'
  }</div>
      <div id="add-friend" style="width: 77px;line-height: 33px;background: #4165F0;border-radius: 17px;border: 1px solid #4165F0;text-align: center;font-size: 15px;color: white;font-weight: 500;cursor: pointer">${
    hasFriend(item.id) ? '去聊天' : '加好友'
  }</div>
    </div>
  </div>
  <div style="position: absolute;z-index: 3;width: 10px;height: 10px;background: white;left: 50%;bottom: 5px;transform: translateX(-50%) rotate(45deg)"></div>
</div>`
}
const getActivityCardContent = (item = {}) => {
  return `<div style="position: relative;width: 398px;height: 165px;">
  <div style="display: flex; width: 398px;height: 158px;box-sizing: border-box;box-shadow: 0 0 10px 0 rgba(0,0,0,0.11);border-radius: 12px;background: white;position: relative;z-index: 2;padding: 16px">
    <img src="${
    item.pic
  }" style="width: 110px;height: 126px;border-radius: 12px;margin-right: 12px"  alt="" />
    <div style="flex: 1;">
      <div style="display: flex;justify-items: center;align-items: center;margin-bottom: 8px;">
        <div style="line-height: 22px;font-size: 16px;color: #333333;width: max-content;margin-right: 8px">${calculateTimestamp(
    item
  )}</div>
        <div style="flex: 1;display: flex;justify-content: flex-end;">
          <div id="check-activity" style="cursor: pointer;width: max-content;color: #4165F0;font-size: 14px;">查看更多</div>
        </div>
      </div>
      <div style="font-size: 16px; color: #333333;margin-bottom: 8px;height: 44px;line-height: 22px;font-weight: 600;" class="ellipsis2">${
    item.title
  }</div>
      <div style="display: flex;align-items: center;">
        <img style="width: 20px;height: 20px;margin-right: 3px;" src="${USER}" alt="">
        <div style="flex: 1;font-size: 14px;color: #333333;">${
    item.users?.length || 0
  } 个人</div>
        <div id="join" style="width: 77px;line-height: 33px;background: #4165F0;border-radius: 17px;border: 1px solid #4165F0;text-align: center;font-size: 15px;color: white;font-weight: 500;cursor: pointer">加入</div>
      </div>
    </div>
  </div>
  <div style="position: absolute;z-index: 3;width: 10px;height: 10px;background: white;left: 50%;bottom: 5px;transform: translateX(-50%) rotate(45deg)"></div>
</div>`
}

const hasFriend = (id) => {
  return messageList.value.some((item) => item.memberId === id)
}

const createUserCard = () => {
  userCardMarker = new AMap.Marker({
    position: [116.403322, 39.920255],
    content: getUserCardContent(),
    offset: new AMap.Pixel(-189, -280),
    zIndex: 100,
    cursor: 'unset',
  })
  userCardMarker.hide()
  userCardMarker.on('click', onUserCardClick)
  map.add(userCardMarker)
}

const onMapClick = () => {
  if (hasMarkerActive.value) {
    userCardMarker.hide()
    markerList.value.forEach((item) => {
      item.marker.setOptions({
        content: getMarkerContent(item, colorMap[item.itemType], item.itemType),
        offset: new AMap.Pixel(-24, -56),
        zIndex: 1,
      })
    })
    hasMarkerActive.value = false
  }
  allRouteMarkers.forEach((item) => {
    item.marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, 0),
      content: '',
    })
  })
}

const onMarkerClick = async (e) => {
  if (!token.value) {
    loginVisible.value = true
    return
  }
  const target = e.target.getExtData()
  userCardMarker.hide()
  markerList.value.forEach((item) => {
    if (item.id === target.id) {
      target.marker.setOptions({
        content: getMarkerActiveContent(item, colorMap[item.itemType], item.itemType),
        offset: new AMap.Pixel(-43, -101),
        zIndex: 100,
      })
      map.setCenter([item.longitude, item.latitude])
      hasMarkerActive.value = true
    } else {
      item.marker.setOptions({
        content: getMarkerContent(item, colorMap[item.itemType], item.itemType),
        offset: new AMap.Pixel(-24, -56),
        zIndex: 1,
      })
    }
  })
  let options = {}
  if (target.itemType === 0) {
    const user = await getUserDetailInfo(target.externalId)
    options = {
      content: getUserCardContent(user),
      offset: new AMap.Pixel(-189, -280),
      zIndex: 100,
      extData: user,
    }
  } else if (target.itemType === 1) {
    const activity = await getActivityDetailInfo(target.externalId)
    options = {
      content: getActivityCardContent(activity),
      offset: new AMap.Pixel(-198, -272),
      zIndex: 100,
      extData: activity,
    }
  } else {
    return
  }
  await userCardMarker.setOptions(options)
  userCardMarker.setPosition([target.longitude, target.latitude])
  userCardMarker.show()
}

const onUserCardClick = (e) => {
  const targetDom = e.originEvent.target
  const item = userCardMarker.getExtData()
  const target = targetDom.getAttribute('id')
  if (target === 'add-friend') {
    openIM({
      memberId: item.id,
      avatar: item.avatar,
      memberName: item.nickname,
      sex: item.sex,
      mark: item.mark,
    })
  } else if (target === 'check-activity' || target === 'join') {
    activityDetail.value = item.details || ''
    drawerVisible.value = true
  }
}

const onRouteMarkerClick = (e) => {
  const target = e.target.getExtData()
  allRouteMarkers.forEach((item) => {
    if (item.latitude === target.latitude && item.longitude === target.longitude) {
      item.marker.setLabel({
        direction:'top',
        offset: new AMap.Pixel(0, 0),
        content: `<div style="box-sizing: border-box;box-shadow: 0 0 10px 0 rgba(0,0,0,0.11);border-radius: 12px;background: white;padding: 6px 12px;font-size: 12px; font-weight: bold; color: #333333;line-height: 22px;">${item.name}</div>`,
      })
      map.setZoomAndCenter(18, [item.longitude, item.latitude])
    } else {
      item.marker.setLabel({
        direction: 'top',
        offset: new AMap.Pixel(0, 0),
        content: '',
      })
    }
  })
}

const getUserDetailInfo = async (id) => {
  return get(`/app-api/member/user/get-member-user-info`, { id })
}
const getActivityDetailInfo = async (id) => {
  return get(`/app-api/crush/activity/detail`, { id })
}

const sendMessage = async (content, type) => {
  loadingSend.value = true
  let params = {
    toUid: imUserInfo.value.memberId || imUserInfo.value.id,
    type,
    text: '',
    attrs: '',
  }
  if (type === 1) {
    params.text = content
  } else {
    params.text = content
    params.attrs = content
  }
  await post(`/app-api/crush/member-message/send`, params).catch(() => {
    loadingSend.value = false
  })
  if (type === 1) textarea.value = undefined
  await getIMMessageList().finally(() => {
    loadingSend.value = false
  })
}

const sendText = (e) => {
  if (e.keyCode === 13 && e.shiftKey) return
  e?.preventDefault()
  e?.stopPropagation()
  if (!textarea.value) return
  sendMessage(textarea.value, 1)
}

const sendEmoji = (emoji) => {
  emojiPopoverRef.value?.hide?.()
  sendMessage(emoji, 1)
}

const getMapMarker = async () => {
  const center = map.getCenter()
  markerList.value = await get(`/app-api/crush/map-item/around`, {
    longitude: center.lng,
    latitude: center.lat,
    distance: 20000,
    limit: 100,
  })
  markerList.value.forEach((item, index) => {
    // if (index === markerList.value.length - 1)
      // map.setCenter([item.longitude, item.latitude])
    setMapMarker(item, index)
  })
}

const afterUpload = (e) => {
  sendMessage(e.data, 2)
}

const afterAvatarUpload = (e) => {
  userInfoSetting.value.avatar = e.data
}

const updateUserInfo = async () => {
  if (
    !userInfoSetting.value.nickname ||
    !userInfoSetting.value.sex ||
    !userInfoSetting.value.avatar
  )
    return
  await put(`/app-api/member/user/update`, userInfoSetting.value)
  ElMessage.success({
    message: '修改成功',
  })
  userInfo.value = userInfoSetting.value
  infoVisible.value = false
}

const sendAiText = async (e) => {
  if (e?.keyCode === 13 && e?.shiftKey) return
  e?.preventDefault()
  e?.stopPropagation()
  if (!textarea.value) return
  const prompt = textarea.value + ''
  loadingSend.value = true
  try {
    const currentTime = new Date().getTime()
    const controller = new AbortController()
    aiMessageList.value.push({ ai: false, text: prompt, time: currentTime })
    textarea.value = undefined
    const response = await fetch(
      baseUrl+ '/app-api/crush/ai/chat',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Tenant-Id': '1',
          Authorization: `Bearer ${token.value}`,
        },
        signal: controller.signal,
        body: JSON.stringify({
          prompt: prompt,
          appId: 'f94a69b959c743a8823074d8dc2deedb',
        }),
      }
    )
    if (!response.ok) {
      ElMessage.error({
        message: '系统繁忙，请稍后再试',
      })
      return
    }
    aiMessageList.value.push({ ai: true, text: '', time: currentTime })
    const currentIndex = aiMessageList.value.length -1
    // 获取响应流
    const decoder = new TextDecoder('UTF-8')
    const reader = response.body.getReader()

    // 用于累计接收到的数据
    let accumulatedText = ''

    // 方法1 for await of
    // const stream = response.body.pipeThrough(new TextDecoderStream());
    // for await (const chunk of stream) {
    //   // chunk 是按顺序接收的完整数据块（字符串）
    //   console.log('接收到数据块:', chunk);
    //   // 累加并渲染数据
    //   const newText = extractText(chunk)
    //   if (newText) {
    //     console.log(newText);
    //     accumulatedText += extractText(chunk);
    //     aiMessageList.value[aiMessageList.value.length - 1].text = renderMarkdown(accumulatedText.replaceAll('\\n', '\n'))
    //   }
    //   if (chunk.includes('"finish_reason":"stop"')) break;
    // }
    // console.log('流读取完成');
    // aiMessageList.value[aiMessageList.value.length - 1].json = parseJsonFromMarkdown(accumulatedText)
    // console.log(aiMessageList.value[aiMessageList.value.length - 1].json);
    // loadingSend.value = false;

    // 方法2 reader.read().then
    async function read() {
      let done1 = false
      while (!done1) {
        const { done, value } = await reader?.read()
        done1 = done
        if (done1) {
          console.log('流读取完成')
          controller.abort()
          reader.releaseLock()

          renderToAI(accumulatedText, currentIndex, true)

          loadingSend.value = false
          loadingLine.value = false
          return
        }

        // 解码二进制数据为文本
        const chunk = decoder.decode(value, { stream: true })
        // console.log('chunk:===>', chunk)
        // 累加并渲染数据
        const newText = extractText(chunk)
        // console.log('newText:===>', newText)

        if (newText) {
          accumulatedText += newText
          renderToAI(accumulatedText, currentIndex)
        }
      }
    }
    await read()

    // 方法3 while (true)
    // while (true) {
    //   // 读取数据块
    //   const {done, value} = await reader.read();
    //
    //   if (done) {
    //     console.log('流读取完成');
    //     aiMessageList.value[aiMessageList.value.length - 1].json = parseJsonFromMarkdown(accumulatedText)
    //     console.log(aiMessageList.value[aiMessageList.value.length - 1].json);
    //     loadingSend.value = false;
    //     reader.releaseLock();
    //     break;
    //   }
    //
    //   // 解码二进制数据为文本
    //   const chunk = decoder.decode(value, {stream: true});
    //   // 累加并渲染数据
    //   accumulatedText += extractText(chunk);
    //   aiMessageList.value[aiMessageList.value.length - 1].text = renderMarkdown(accumulatedText.replaceAll('\\n', '\n'))
    //   scrollToBottom('.ai-content')
    // }
  } catch (e) {
    console.log(e)
    ElMessage.error({
      message: '系统繁忙，请稍后再试',
    })
  }
}

const renderToAI = async (text, index, ready=false) => {
  const currentMsg = aiMessageList.value[index]
  // 将回答和json数据分离
  const { jsonBlocks, remainingText } = processMarkdownText(
    text.replaceAll('\\n', '\n')
  )
  currentMsg.text = md.render(remainingText)
  currentMsg.ready = ready
  let js = jsonBlocks?.[0] || null
  if (js && ready) {
    const res = await post(`/app-api/crush/ai/batch-geocode`, js)
    currentMsg.json = JSON.parse(res)
  }
}

function extractText(jsonString) {
  try {
    const regex = /"text":"(.*?)"},"usage":/gs;
    let match;
    let result = '';
    while ((match = regex.exec(jsonString)) !== null) {
      result += match[1].replace(/\\n/g, '\n').replace(/\\"/g, '"');
    }
    return result
  } catch (error) {
    console.log('error', error)
    return ''
  }
}

const openVideo = async () => {
  if (loadingVideo.value) return
  loadingVideo.value = true
  const { lat, lng } = map.getCenter()
  const res = await get('/app-api/crush/videos/page-around', {
    latitude: lat,
    longitude: lng,
    distance: 50000,
    pageNo: 1,
    pageSize: 10,
  }).finally(() => {
    loadingVideo.value = false
  })
  videoList.value = res.list || []
  videoVisible.value = true
}

const search = () => {
  if (!token.value) {
    searchKey.value = ''
    loginVisible.value = true
    return
  }
  if (!searchKey.value) return
  aiVisible.value = true
  textarea.value = searchKey.value + ''
  searchKey.value = ''
  sendAiText()
}

const createMapLine = (routeData) => {
  aiVisible.value = false
  clearMapLine()
  currentLineMap.value = routeData || null
  if (!currentLineMap.value) return
  if (routeData?.recommends?.length > 0) {
    routeData.recommends.forEach((item, index) => {
      const marker = new AMap.Marker({
        position: new AMap.LngLat(item.longitude, item.latitude),
        icon: Location,
        anchor:'bottom-center',
        offset: new AMap.Pixel(0, 0),
        extData: item,
        zIndex: 2,
        clickable: true,
      })
      marker.on('click', onRouteMarkerClick)
      map.add(marker)
      allRouteMarkers.push({ ...item,marker: marker })
      if (!index) map.setCenter([item.longitude, item.latitude])
    })
    showCLearBtn.value = true;
    resetMapLine()
    return;
  }
  if (!routeData.route) return
  const days = Object.keys(routeData.route).filter(day => routeData.route[day])
  if (currentDay.value !== days[0]) {
    currentDay.value = days[0]
  } else {
    const allAddr = currentLineMap.value.route[days[0]]
    if (!allAddr) return
    // 根据起终点经纬度规划驾车导航路线
    if (allAddr.length > 1) {
      let waypoints = allAddr.slice(1, -1);
      driving.search(
        new AMap.LngLat(allAddr[0].longitude, allAddr[0].latitude),
        new AMap.LngLat(allAddr[allAddr.length - 1].longitude, allAddr[allAddr.length - 1].latitude),
        {
          waypoints: waypoints.map((item) => {
            return new AMap.LngLat(item.longitude, item.latitude)
          })
        }
      )
    } else {
      map.setCenter([allAddr[0].longitude, allAddr[0].latitude])
    }
    allAddr.forEach((item) => {
      const marker = new AMap.Marker({
        position: new AMap.LngLat(item.longitude, item.latitude),
        icon: Location,
        anchor:'bottom-center',
        offset: new AMap.Pixel(0, 0),
        extData: item,
        zIndex: 2,
        clickable: true,
      })
      marker.on('click', onRouteMarkerClick)
      map.add(marker)
      allRouteMarkers.push({ ...item,marker: marker })
    })
  }
  showDayBtn.value = true
  resetMapLine()
}

const clearMapLine = () => {
  if (driving) driving.clear()
  currentLineMap.value = null
  showDayBtn.value = false
  showCLearBtn.value = false
  allRouteMarkers.forEach((item) => {
    map.remove(item.marker)
  })
  allRouteMarkers = []
}

function processMarkdownText(text) {
  const jsonRegex = /```json([\s\S]*?)```/gs
  const jsonBlocks = []
  let remainingText = text

  // 提取JSON代码块并从原文中移除
  let hasMatchJson = false
  let match
  while ((match = jsonRegex.exec(text)) !== null) {
    loadingLine.value = false
    hasMatchJson = true;
    let json = ''
    let jsonContent = match[1].trim()
    try {
      json = JSON.parse(jsonContent)
    } catch (e) {
      // 如果直接解析失败，尝试修复转义的双引号
      try {
        let fixedJson = jsonContent.replace(/\\"/g, '"')
        // 修复缺失的逗号
        fixedJson = fixedJson.replace(/(})(\s*)(\{)/g, '$1,$3')
        fixedJson = fixedJson.replace(/(})(\s*)(")/g, '$1,$2$3')
        fixedJson = fixedJson.replace(/(})(\s*)(])/g, '$1,$3')
        // 修复不完整的属性（如"longitude 120.632013"）
        fixedJson = fixedJson.replace(
          /"longitude\s+(\d+\.\d+)"/g,
          '"longitude": $1'
        )
        fixedJson = fixedJson.replace(
          /"latitude\s+(\d+\.\d+)"/g,
          '"latitude": $1'
        )
        fixedJson = fixedJson.replaceAll(/},]/g, '}]')
        // console.log('优化过的json', fixedJson)
        json = JSON.parse(fixedJson)
      } catch (e) {
        console.log(match[1].trim())
        console.error('JSON解析失败:', e)
      }
    }
    if (json) jsonBlocks.push(json)
    remainingText = remainingText.replace(match[0], '')
  }

  if (!hasMatchJson) {
    loadingLine.value = true;
    const index = remainingText.indexOf('```json');
    remainingText = index !== -1 ? remainingText.substring(0, index).trim() : remainingText;
  }

  remainingText = remainingText
    .replace('以下是路线坐标信息（JSON格式）：', '')
    .replace('详细坐标信息（JSON格式）：', '')
    .replace('以下是每日景点坐标信息：', '')
    .replace('路线规划JSON数据：', '')
    .replace('以下是路线坐标的JSON格式：', '')
    .replace(/^\n+/, '') // 移除开头的换行符
    .replace(/\n+$/, '') // 移除结尾的换行符

  return {
    jsonBlocks,
    remainingText,
  }
}

function calculateTimestamp({ createTime, status }) {
  if (!createTime) {
    return statusMap[status] || ''
  }
  const todayZero = new Date().setHours(0, 0, 0, 0)
  const thisYear = new Date(
    new Date().getFullYear(),
    0,
    1,
    0,
    0,
    0,
    0
  ).getTime()
  const target = new Date(createTime)

  const oneDay = 24 * 60 * 60 * 1000
  const oneWeek = 7 * oneDay

  const diff = todayZero - target.getTime()

  function formatNum(num) {
    return num < 10 ? '0' + num : num.toString()
  }

  if (diff <= 0) {
    // today, only display hour:minute
    return `${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`
  } else if (diff <= oneDay) {
    // yesterday, display yesterday:hour:minute
    return `昨天 ${formatNum(target.getHours())}:${formatNum(
      target.getMinutes()
    )}`
  } else if (diff <= oneWeek - oneDay) {
    // Within a week, display weekday hour:minute
    const weekdays = [
      '星期日',
      '星期一',
      '星期二',
      '星期三',
      '星期四',
      '星期五',
      '星期六',
    ]
    const weekday = weekdays[target.getDay()]
    return `${weekday} ${formatNum(target.getHours())}:${formatNum(
      target.getMinutes()
    )}`
  } else if (target.getTime() >= thisYear) {
    // Over a week, within this year, display mouth/day hour:minute
    return `${target.getMonth() + 1}/${target.getDate()} ${formatNum(
      target.getHours()
    )}:${formatNum(target.getMinutes())}`
  } else {
    // Not within this year, display year/mouth/day hour:minute
    return `${target.getFullYear()}/${
      target.getMonth() + 1
    }/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(
      target.getMinutes()
    )}`
  }
}

const goCenter = () => {
  if (markerList.value?.length) {
    const { longitude, latitude } = markerList.value[markerList.value.length - 1]
    map.setCenter([longitude, latitude])
    map.setZoom(18)
  } else {
    map.setCenter([121.614253, 29.861748])
    map.setZoom(18)
  }
}

const resetMapLine = () => {
  allRouteMarkers.forEach((item) => {
    item.marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, 0),
      content: '',
    })
  })
  map.setFitView(allRouteMarkers.map(item=>item.marker))
}

const updateAIText = throttleNextTick((index)=> {
  aiMessageList.value[index].showBtn = false
  scrollToBottom('.ai-content')
})

const textAllShow = (index) => {
  aiMessageList.value[index].showBtn = true
  setTimeout(() => {
    scrollToBottom('.ai-content')
  }, 100)
}

function throttleNextTick(callback) {
  let timer = null;
  let lastExecTime = 0;
  let lastArgs = null;

  const execute = () => {
    lastExecTime = Date.now();
    nextTick(() => {
      callback(...lastArgs);
    });
  };

  return function throttled(...args) {
    const now = Date.now();
    lastArgs = args;
    if (now - lastExecTime > 500) {
      clearTimeout(timer);
      timer = null;
      execute();
    } else if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        execute();
      }, 500 - (now - lastExecTime));
    }
  };
}

function arabicToChinese(num) {
  if (isNaN(num) || num === null) return '';

  const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const units = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '兆'];

  num = Math.abs(num);
  let result = '';
  let numStr = num.toString();

  for (let i = 0; i < numStr.length; i++) {
    const digit = parseInt(numStr[i]);
    const position = numStr.length - i - 1;

    if (digit !== 0) {
      result += digits[digit] + units[position];
    } else {
      // 处理零的情况：避免连续多个零，或在单位为万/亿时补零
      if (i < numStr.length - 1 && parseInt(numStr[i + 1]) !== 0 && !result.endsWith('零')) {
        result += '零';
      }
      // 处理万/亿单位
      if (position % 4 === 0 && position > 0) {
        result += units[position];
      }
    }
  }

  // 特殊处理一十X的情况
  if (result.startsWith('一十')) {
    result = result.substring(1);
  }

  return result;
}

</script>
<style>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}
.map {
  width: 100%;
  height: 100vh;
  transition: opacity 3s;
  opacity: 0;
}
.lazy-in {
  animation: load-in;
  opacity: 1;
}
.header {
  height: 70px;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 161;
  background: #161822;
  transition: top 0.5s;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  animation: header-in 0.5s;
}
.search {
  width: 244px;
  height: 38px;
  background: #3a3a43;
  border-radius: 20px;
  position: relative;
}
.search::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 26px;
  height: 26px;
  background: url(./assets/ic_search@2x.png) no-repeat;
  background-size: 26px 26px;
}
.search .el-input__wrapper {
  background: none;
  box-shadow: none;
}
.search input {
  height: 38px;
  line-height: 38px;
  padding-left: 30px;
  font-size: 14px;
}
.user {
  height: 38px;
  background: #3a3a43;
  border-radius: 20px;
  box-sizing: border-box;
  padding: 0 16px 0 44px;
  line-height: 38px;
  position: relative;
  font-weight: 500;
  font-size: 16px;
  color: #eaeaeb;
  cursor: pointer;
}
.user::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 26px;
  height: 26px;
  background: url(./assets/ic_login@2x.png) no-repeat;
  background-size: 26px 26px;
}
.user-info {
  padding: 0 16px 0 44px;
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
}
.user-info::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  background: url(./assets/ic_more@2x.png) no-repeat;
  background-size: 16px 16px;
}
.user-info-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 6px;
}
.user-info-name {
  font-weight: 500;
  font-size: 16px;
  color: #eaeaeb;
  line-height: 38px;
  flex: 1;
  padding-right: 6px;
}
.el-popper.is-light {
  border-radius: 16px;
}
.el-popper.is-light,
.el-popper.is-light > .el-popper__arrow:before {
  background: #252631;
  border-color: #252631;
  padding: 16px;
}
.left-bar {
  width: 96px;
  position: fixed;
  top: 70px;
  left: 0;
  bottom: 48px;
  z-index: 161;
  background: #161822;
  transition: all 0.5s;
  box-sizing: border-box;
  border-top: 1px solid #3b3e41;
  border-bottom: 1px solid #3b3e41;
  padding-top: 8px;
  animation: left-bar-in 0.5s;
}
.expand {
  width: 28px;
  height: 28px;
  background: url(./assets/ic_expand@2x.png) no-repeat;
  background-size: 24px 24px;
  cursor: pointer;
  margin: 0 0 0 34px;
  transition: all 0.5s;
}
.msg-count {
  line-height: 22px;
  font-weight: 500;
  font-size: 16px;
  color: #eaeaeb;
  position: absolute;
  left: -200px;
  top: 14px;
  white-space: nowrap;
  transition: left 0.5s;
}
.ai {
  width: 52px;
  height: 52px;
  background: #28282d;
  border-radius: 12px;
  margin-left: 22px;
  margin-top: 20px;
  cursor: pointer;
  transition: all 0.5s;
  overflow: hidden;
  display: flex;
  position: relative;
}
.bar-line {
  margin: 12px 22px;
  height: 1px;
  background: #3b3e41;
  opacity: 1;
  transition: opacity 0.5s;
}
.ai img {
  width: 56px;
  height: 56px;
  transition: all 0.5s;
  margin-right: 5px;
  transform: translateX(-3px);
}
.ai div {
  flex: 0;
  line-height: 42px;
  font-weight: 500;
  font-size: 18px;
  color: #959ba3;
  white-space: nowrap;
}
.user-list {
  height: calc(100% - 130px);
  overflow-y: scroll;
}
.user-list::-webkit-scrollbar {
  width: 4px;
  background: transparent;
  border-radius: 4px;
}
.user-list::-webkit-scrollbar-thumb {
  width: 4px;
  background: #3b3e41;
  border-radius: 4px;
}
.user-item {
  width: 80px;
  height: 72px;
  background: transparent;
  border-radius: 0;
  cursor: pointer;
  padding: 12px 22px;
  transition: all 0.5s;
  overflow: hidden;
  display: flex;
  position: relative;
}
.user-item > img {
  width: 52px;
  height: 52px;
  transition: all 0.5s;
  border-radius: 50%;
  margin-right: 14px;
  position: relative;
}
.online-dot {
  position: absolute;
  left: 60px;
  bottom: 6px;
  width: 14px;
  height: 14px;
  background: #30d074;
  border-radius: 50%;
  border: 3px solid #161822;
  box-sizing: border-box;
  transition: all 0.5s;
}
.user-item .user-nickname {
  flex: 0;
  line-height: 42px;
  font-weight: 500;
  font-size: 18px;
  color: #959ba3;
  white-space: nowrap;
  opacity: 0;
}
.user-item .user-msg-count {
  position: absolute;
  left: 220px;
  top: 50%;
  transform: translateY(-50%);
  background: #ff4132;
  border-radius: 10px;
  font-weight: 600;
  font-size: 11px;
  color: #ffffff;
  line-height: 16px;
  padding: 0 4px;
}
.user-checked > img {
  border-radius: 16px;
}

.user-checked::before {
  content: '';
  position: absolute;
  left: 16px;
  top: 6px;
  right: 6px;
  bottom: 6px;
  width: 64px;
  height: 64px;
  background: transparent;
  border-radius: 16px;
  border: 2px solid #4165f0;
  box-sizing: border-box;
  transition: all 0.5s;
  opacity: 1;
}
.user-checked::after {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  bottom: 13px;
  width: 4px;
  height: 40px;
  background: #4165f0;
  border-radius: 0 3px 3px 0;
  box-sizing: border-box;
  transition: all 0.5s;
  opacity: 1;
}

.left-bar-expand {
  width: 280px;
}
.left-bar-expand .expand {
  margin: 0 0 0 235px;
  transform: rotate(180deg);
}
.left-bar-expand .msg-count {
  left: 22px;
}
.left-bar-expand .ai {
  background: transparent;
  padding: 5px;
  width: 236px;
}
.left-bar-expand .ai img {
  width: 46px;
  height: 46px;
}
.left-bar-expand .ai div {
  flex: 1;
}
.left-bar-expand .bar-line {
  opacity: 0;
}
.left-bar-expand .user-item {
  border-radius: 12px;
  padding: 12px;
  margin: 4px 0 4px 10px;
  width: 260px;
  height: 68px;
}
.left-bar-expand .user-item > img {
  width: 42px;
  height: 42px;
}
.left-bar-expand .user-item .online-dot {
  left: 44px;
  bottom: 10px;
}
.left-bar-expand .user-item .user-nickname {
  flex: 1;
  opacity: 1;
}
.left-bar-expand .user-checked {
  background: #28282d;
}
.left-bar-expand .user-checked > img {
  border-radius: 50%;
}
.left-bar-expand .user-checked::before,
.left-bar-expand .user-checked::after {
  opacity: 0;
}

.footer {
  height: 48px;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 161;
  background: #161822;
  animation: footer-in 0.5s;
  text-align: center;
  font-size: 12px;
  padding-top: 4px;
  color: #888888;
}
.footer a {
  color: #888888;
}
.toolbar {
  height: 48px;
  position: fixed;
  top: 92px;
  right: -72px;
  z-index: 161;
  transition: right 0.5s;
}
.toolbar-center {
  top: unset;
  bottom: 94px;
}
.toolbar-in {
  right: 16px;
}
.play {
  width: 56px;
  height: 56px;
  background: url(./assets/ic_paly@2x.png) no-repeat;
  background-size: 56px 56px;
  cursor: pointer;
}
.play:hover {
  background: url(./assets/ic_paly_hover@2x.png) no-repeat;
  background-size: 56px 56px;
}
.setting {
  margin-top: 16px;
  width: 56px;
  height: 56px;
  background: url(./assets/ic_set@2x.png) no-repeat;
  background-size: 56px 56px;
  cursor: pointer;
}
.setting:hover {
  background: url(./assets/ic_set_hover@2x.png) no-repeat;
  background-size: 56px 56px;
}
.go-back {
  margin-top: 16px;
  width: 56px;
  height: 56px;
  background: url(./assets/goback.png) no-repeat rgba(0, 0, 0, 0.7);
  background-size: 36px 36px;
  background-position: center;
  cursor: pointer;
  border-radius: 50%;
}
.go-back:hover {
  background: url(./assets/goback.png) no-repeat #007aff;
  background-size: 36px 36px;
  background-position: center;
}

.login-dialog {
  background: transparent;
  position: relative;
  height: 531px;
  box-shadow: none;
}
.login-dialog::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 531px;
  background: url(./assets/bg@2x.png) no-repeat;
  background-size: 810px 531px;
}
.login-close1 {
  position: absolute;
  right: 38px;
  top: -8px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  z-index: 2;
}
.login-close {
  position: absolute;
  right: 12px;
  top: -30px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  z-index: 2;
}

.login-content {
  display: flex;
  margin-top: 28px;
  padding: 0 60px;
  position: relative;
}
.login-left {
  width: 318px;
}

.login-right {
  flex: 1;
  position: relative;
  margin-top: 140px;
  margin-right: 34px;
}
.login-input {
  background: #272C39;
  border-radius: 8px;
  padding: 12px;
  color: #333333;
  margin-top: 12px;
}
.login-input .el-input__wrapper {
  background: none;
  box-shadow: none;
  padding: 0;
}
.login-input input {
  font-size: 14px;
  line-height: 20px;
  color: #ffffff;
}
.login-code {
  margin-top: 16px;
  margin-bottom: 60px;
}
.login-code input {
  padding-right: 120px;
}
.get-code {
  position: absolute;
  top: 100px;
  right: 12px;
  font-size: 14px;
  color: #4165f0;
  cursor: pointer;
}
.get-code-disabled {
  color: #999999;
  cursor: not-allowed;
}
.login-btn {
  width: 100%;
  line-height: 47px;
  background: #4165f0;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  text-align: center;
  cursor: pointer;
  transition: opacity 0.3s;
}
.login-btn-disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.user-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}
.user-content > img {
  width: 50px;
  height: 50px;
  margin-right: 12px;
  border-radius: 50%;
}
.user-content-info {
  flex: 1;
  font-size: 16px;
  line-height: 20px;
  color: #eaeaeb;
}
.user-content-info img {
  width: 18px;
  height: 18px;
  margin-top: 6px;
}
.user-logout {
  height: 42px;
  line-height: 42px;
  background: #2e2f38;
  border-radius: 12px;
  font-size: 14px;
  color: #999999;
  padding-left: 40px;
  cursor: pointer;
  position: relative;
}
.user-logout::before {
  content: '';
  position: absolute;
  top: 10px;
  left: 13px;
  width: 22px;
  height: 22px;
  background: url(./assets/ic_exit@2x.png) no-repeat;
  background-size: 22px 22px;
}

.im-dialog {
  background: #252631;
  border-radius: 24px;
  position: relative;
  padding: 0;
}
.im-dialog .el-dialog__header {
  padding: 0;
}
.im-close {
  position: absolute;
  top: 8px;
  right: 26px;
  width: 40px;
  height: 40px;
  cursor: pointer;
}
.im-title {
  line-height: 56px;
  padding-left: 24px;
  font-weight: 500;
  font-size: 20px;
  color: #ffffff;
}
.im-content,
.ai-content {
  height: 500px;
  overflow-y: scroll;
  padding: 18px 26px;
}
.im-content::-webkit-scrollbar,
.ai-content::-webkit-scrollbar {
  width: 4px;
  background: transparent;
  border-radius: 4px;
}
.im-content::-webkit-scrollbar-thumb,
.ai-content::-webkit-scrollbar-thumb {
  width: 4px;
  background: #3b3e41;
  border-radius: 4px;
}
.im-content > div,
.ai-content > div {
  margin-bottom: 22px;
}

.im-msg-other,
.ai-msg-other {
  display: flex;
}
.im-msg-i {
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-start;
}
.im-msg-content img {
  width: 22px;
  height: 22px;
}
.im-msg-img {
  width: 160px;
  height: auto;
  border-radius: 12px;
}
.im-msg-video {
  width: 160px;
  height: auto;
  border-radius: 12px;
}
.im-msg-other .im-msg-icon,
.ai-msg-other .im-msg-icon {
  width: 46px;
  height: 46px;
  margin-right: 12px;
  border-radius: 50%;
}
.im-msg-i .im-msg-icon {
  width: 46px;
  height: 46px;
  margin-left: 12px;
  border-radius: 50%;
}
.ai-msg-other .im-msg-content {
  max-width: 384px;
  background: transparent;
  border-radius: 4px 19px 19px 19px;
  padding: 12px;
  line-height: 22px;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  word-break: break-all;
}
.im-msg-other .im-msg-content {
  max-width: 384px;
  background: #41424b;
  border-radius: 4px 19px 19px 19px;
  padding: 12px;
  line-height: 22px;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  word-break: break-all;
}
.im-msg-i .im-msg-content {
  max-width: 384px;
  background: #4165f0;
  border-radius: 19px 4px 19px 19px;
  padding: 12px;
  line-height: 22px;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  word-break: break-all;
}
.im-msg-btn {
  width: 92px;
  line-height: 33px;
  border-radius: 17px;
  border: 1px solid #ffffff;
  font-weight: 500;
  font-size: 15px;
  color: #ffffff;
  text-align: center;
  margin-left: 70px;
  cursor: pointer;
}
.im-footer {
  padding: 26px;
}
.im-footer-content {
  background: #41424b;
  border-radius: 12px;
  padding: 12px;
}
.ai-footer-content {
  display: flex;
  align-items: center;
  background: #41424b;
  border-radius: 12px;
  padding: 12px;
  position: relative;
}
.im-footer-toolbar {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-top: 6px;
}
.im-footer-toolbar .toolbar-item,
.ai-footer-content .toolbar-item {
  width: 22px;
  height: 22px;
  margin-left: 12px;
  cursor: pointer;
}
.toolbar-emoji {
  background: url('./assets/ic_emoji@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-emoji:hover {
  background: url('./assets/ic_emoji1@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-file {
  background: url('./assets/ic_img@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-file:hover {
  background: url('./assets/ic_img1@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-send-disabled {
  background: url('./assets/ic_send@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-send {
  background: url('./assets/ic_sending1@2x.png') no-repeat;
  background-size: 22px 22px;
}
.toolbar-send:hover {
  background: url('./assets/ic_sending1_hover@2x.png') no-repeat;
  background-size: 22px 22px;
}
.ai-footer-content .el-textarea__inner {
  min-height: unset;
}
.im-footer-content .el-textarea__inner,
.ai-footer-content .el-textarea__inner, .el-textarea.is-disabled .el-textarea__inner {
  background: transparent;
  border: none;
  padding: 0;
  box-shadow: none;
  resize: none;
  font-size: 14px;
  color: #ffffff;
}
.im-footer-content .el-textarea__inner::-webkit-scrollbar,
.ai-footer-content .el-textarea__inner::-webkit-scrollbar {
  width: 4px;
  background: transparent;
  border-radius: 4px;
}
.im-footer-content .el-textarea__inner::-webkit-scrollbar-thumb,
.ai-footer-content .el-textarea__inner::-webkit-scrollbar-thumb {
  width: 4px;
  background: #252631;
  border-radius: 4px;
}

.video-dialog {
  background: #252631;
  border-radius: 30px;
  position: relative;
  padding: 0;
  overflow: hidden;
  margin-right: 16px !important;
}
.video-dialog .el-dialog__header {
  padding: 0;
}
.video-close {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  z-index: 100;
}
.video-content {
  width: 100%;
  height: 850px;
  overflow: hidden;
}
.swiper-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.page-ctr {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateX(-50%);
  z-index: 100;
  width: 36px;
  height: 80px;
  background: #2b2b35;
  border-radius: 18px;
  padding: 6px;
}
.page-ctr img {
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.page-ctr-pre,
.page-ctr-nxt-disabled {
  transform: rotate(180deg);
}
.page-ctr-pre-disabled {
  transform: rotate(0deg) !important;
}
.page-ctr-nxt,
.page-ctr-nxt-disabled {
  margin-top: 16px;
}

.emoji-box {
  display: grid;
  grid-template-columns: repeat(12, 26px);
  grid-gap: 16px;
}
.emoji-box img {
  width: 26px;
  height: 26px;
  cursor: pointer;
}
.emoji-popper {
  transform: translate(-183px, -52px);
  box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.35) !important;
  border-radius: 12px !important;
  background: #252631 !important;
}
.emoji-popper .el-popper__arrow:before {
  content: unset;
}

.el-loading-mask {
  background: transparent !important;
}

.ellipsis3 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.ellipsis2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.swiper-activity-content {
  width: 375px;
  height: 390px;
  overflow: hidden;
}
.swiper-activity-item {
  width: 375px;
  height: 390px;
}
.el-drawer__body {
  padding: 0;
}
#swiper-pagination {
  text-align: center;
}
.drawer-close {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 40px;
  height: 40px;
  background: rgba(43, 43, 53, 0.4);
  border-radius: 24px;
  display: flex;
  z-index: 100;
  cursor: pointer;
}
.drawer-close img {
  width: 40px;
  height: 40px;
  margin: auto;
}

.video-info {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100px;
  color: #fff;
  padding: 16px;
  box-sizing: border-box;
  z-index: 101;
}
.video-info .video-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
}
.video-info .video-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 16px;
}

.info-dialog {
  background: #ffffff;
  box-shadow: 0 10px 0 rgba(0, 0, 0, 0.11);
  border-radius: 26px;
  border: 1px solid #eae9eb;
  position: relative;
  padding: 0 0 50px;
}
.info-dialog::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 133px;
  background: url(./assets/info_bg.png) no-repeat;
  background-size: 463px 133px;
}
.info-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
}
.info-avatar img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  cursor: pointer;
}
.info-avatar-tip {
  font-size: 14px;
  color: #333333;
  text-align: center;
  margin-top: 8px;
  margin-bottom: 30px;
}
.info-sex {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18px;
  margin-left: 60px;
  margin-right: 60px;
}

.info-sex > div {
  flex: 1;
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 52px;
  background: #f2f2f4;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 500;
  font-size: 15px;
  color: #333333;
}
.info-sex > div > img {
  width: 30px;
  height: 30px;
  margin-right: 5px;
}
.info-sex .info-sex-active {
  background: linear-gradient(132deg, #4165f0 0%, #80bdff 100%);
  color: #fff;
}
.info-input-content {
  margin-bottom: 36px;
  margin-left: 60px;
  margin-right: 60px;
}
.info-input {
  background: #f2f2f4;
  border-radius: 8px;
  padding: 12px;
  color: #333333;
  margin-bottom: 18px;
}
.info-input .el-input__wrapper,
.info-input .el-textarea__inner {
  background: none;
  box-shadow: none;
  padding: 0;
}
.info-submit {
  line-height: 47px;
  background: rgba(65, 101, 240, 0.4);
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  text-align: center;
  margin-right: 60px;
  margin-left: 60px;
  cursor: pointer;
}
.info-submit-active {
  background: rgba(65, 101, 240);
}

.el-dialog__body {
  position: relative;
  z-index: 3;
}

.header::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  right: 0;
  bottom: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
  transform: rotate(180deg);
}
.header::before {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  left: 0;
  bottom: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
  transform: rotate(90deg);
}
.footer::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  right: 0;
  top: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
  transform: rotate(270deg);
}
.footer::before {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  left: 0;
  top: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
}

.left-bar::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  bottom: -1px;
  right: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
}
.left-bar::before {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  top: -1px;
  right: -8px;
  background: url(./assets/yuanjiao.png) no-repeat;
  background-size: 8px 8px;
  transform: rotate(90deg);
}

.day-tool {
  position: absolute;
  top: 100px;
  left: 50%;
  z-index: 10;
  display: flex;
  transform: translateX(-50%);
  animation: load-in 0.3s ease-in-out;
  width: 90vw;
  justify-content: center;
}

.el-radio-button.is-active .el-radio-button__original-radio:not(:disabled)+.el-radio-button__inner {
  background-color: #161822;
  border-color: #161822;
  box-shadow: -1px 0 0 0 #161822;
}
.el-radio-button__inner:hover {
  color: #161822;
}

.ai-del {
  width: 18px;
  height: 18px;
  background: url(./assets/ic_del@2x.png) no-repeat;
  background-size: 18px 18px;
  cursor: pointer;
  margin-left: 10px;
}
.ai-del:hover {
  background: url(./assets/ic_del@2x1.png) no-repeat;
  background-size: 18px 18px;
}

.amap-marker-label {
  border: none !important;
  background: transparent !important;
}

@keyframes load-in {
  0% {
    opacity: 0;
  }
  20% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
@keyframes header-in {
  0% {
    top: -70px;
  }
  100% {
    top: 0;
  }
}
@keyframes left-bar-in {
  0% {
    left: -96px;
  }
  100% {
    left: 0;
  }
}
@keyframes footer-in {
  0% {
    bottom: -48px;
  }
  100% {
    bottom: 0;
  }
}
</style>
